package com.crazybird.vote.service.vote.impl;

import com.crazybird.vote.config.StartupListenerConfig;
import  com.crazybird.vote.dao.vote.VoteDao;
import  com.crazybird.vote.dao.vote.VoteDetailDao;
import  com.crazybird.vote.dao.vote.VoteRecordDao;
import com.crazybird.vote.dao.vote.dataobject.*;
import com.crazybird.vote.entity.VoteConstant;
import com.crazybird.vote.entity.so.AppException;
import  com.crazybird.vote.service.base.ResponseCode;
import  com.crazybird.vote.service.base.ResponsePageQueryDO;
import  com.crazybird.vote.service.vote.VoteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Component("VoteService")
public class VoteImpl implements VoteService {
	@Resource
	private  VoteDao  voteDao;
	@Resource
	private VoteDetailDao voteDetailDao;
	@Resource
	private VoteRecordDao voteRecordDao;
	@Resource
	private RedisTemplate<String,Integer> redisTemplate;
	private AtomicInteger saveCount=new AtomicInteger(0);
	private Integer saveCountEasy = 0;
	private ValueOperations<String, Integer> integerOperations;

	@Autowired
	public VoteImpl(RedisTemplate redisTemplate) {
		integerOperations = redisTemplate.opsForValue();
	}

	@Override
	public ResponsePageQueryDO<List<VoteActionDO>> getVoteActionList(VoteActionPO po) {
		ResponsePageQueryDO<List<VoteActionDO>> response = new ResponsePageQueryDO<>();
		response.setPageIndex(po.getPageIndex());
		response.setPageSize(po.getPageSize());
		System.out.println(1);
		Integer status = po.getStatus();
		response.setTotal(voteDao.getVoteActionCount(status));
		System.out.println(2);
		if (response.getTotal() > 0 && response.getTotalPage() > po.getPageIndex()) {
			List<VoteActionDO> actionList = voteDao.getVoteActionlist(po);
			response.setDataResult(actionList);
			response.setCode(ResponseCode.SUCCESS);
		} else {
			response.setCode(ResponseCode.ERROR);
			response.setMessage("暂无该类活动");
		}
		return response;
	}
	@Override
	public List<VoteActionDetailDO> getActionDetailList(Long id) {
		List<VoteActionDetailDO> detailList = voteDetailDao.getVoteActionDetail(id);
		return detailList;
	}
	
	@Override
	public List<VoteActionDetailDO> getActionDetailByRank(Long id) {
		List<VoteActionDetailDO> detailList = voteDetailDao.getVoteActionDetailByRank(id);
		return detailList;
	}
	
	@Override
	public VoteActionDO getAction(Long id) {
		return voteDao.getVoteAction(id);
	}

	@Override
	public List<VoteActionHotDTO> getVoteActionHotList() {
		return voteDao.getVoteActionHotList();
	}


	@Override
	public List<VoteActionDetailDO>selectActionDetailByName(VoteActionDetailSearchDO searchDO) {
		List<VoteActionDetailDO> detailList = voteDetailDao.selectActionDetailByName(searchDO);
		return detailList;
	}

	@Override
	public ResponsePageQueryDO<List<VoteActionRecordDTO>> getVoteActionRecord(VoteActionRecordPO po) {
		ResponsePageQueryDO<List<VoteActionRecordDTO>> response = new ResponsePageQueryDO<>();
		List<VoteActionRecordDTO> recordList = new ArrayList<>();
		response.setPageIndex(po.getPageIndex());
		response.setPageSize(po.getPageSize());
		if(po.getType()==1) {
			response.setTotal(voteRecordDao.getUserRecordCount(po.getId()));
		}
		if(po.getType()==2) {
			response.setTotal(voteRecordDao.getActionRecordCount(po.getId()));
		}
		if (response.getTotal() > 0 && response.getTotalPage() > po.getPageIndex()) {
			if(po.getType()==1) {
				recordList = voteRecordDao.getVoteActionUserRecord(po);
			}
			if(po.getType()==2) {
				recordList = voteRecordDao.getVoteActionRecord(po);
			}
			response.setDataResult(recordList);
			response.setCode(ResponseCode.SUCCESS);
		} else {
			response.setCode(ResponseCode.ERROR);
			response.setMessage("无投票记录");
		}
		return response;
	}
	@Override
	public int insertVoteAction(VoteActionDO actionDO) {
		
		return voteDao.insertVoteAction(actionDO);
	}
	@Override
	public int insertVoteActionDetail(VoteActionDetailDO detailDO) {

		return voteDetailDao.insertVoteActionDetail(detailDO);
	}
	@Override
	public int updateVoteAction(VoteActionDO actionDO) {
		
		return voteDao.updateVoteAction(actionDO);
	}
	@Override
	public int updateVoteActionDetail(VoteActionDetailDO detailDO) {
	
		return voteDetailDao.updateVoteActionDetail(detailDO);
	}
	@Override
	public int deleteVoteAction(Long id) {	
		return voteDao.deleteVoteAction(id);
	}
	@Override
	public int deleteVoteActionDetail(Long id) {
		
		return voteDetailDao.deleteVoteActionDetail(id);
	}
	@Override
	public List<VoteActionSlideDO> getVoteActionSlide() {
	
		return voteDao.getVoteActionSlide();
	}
	@Override
	public int addVoteActionSlide(VoteActionSlideDO slideDO) {
		// TODO Auto-generated method stub
		return voteDao.addVoteActionSlide(slideDO);
	}
	@Override
	public int updateVoteActionSlide(VoteActionSlideDO slideDO) {
		// TODO Auto-generated method stub
		return voteDao.updateVoteActionSlide(slideDO);
	}
	@Override
	public int deleteVoteActionSlide(Integer id) {
		// TODO Auto-generated method stub
		return voteDao.deleteVoteActionSlide(id);
	}
	@Override
	public int insertCode(String code) {	
		return voteDao.insertCode(code);
	}
	@Override
	public int deleteCode() {
		return voteDao.deleteCode();
	}
	@Override
	public int updateCode(String code) {
		return voteDao.updateCode(code);
	}
	@Override
	@Cacheable(cacheNames = "codeStatus",key = "#p0")
	public Integer checkCode(String code) {
		
		return voteDao.checkCode(code);
	}
	@Override
	public Integer checkCodeIsNull(String code) {
		Integer status = integerOperations.get(VoteConstant.VOTE_CHECK + code);
		if (status != null){
			return status == 0 ? 1:0;
		}else {
			Integer integer = this.checkCode(code);
			integerOperations.set(VoteConstant.VOTE_CHECK+code,integer);
			if (integer == null) {
				return 0;
			}
			return  1;
		}
//		return voteDao.checkCodeIsNull(code);
	}
	
	@Override
	public int insertTeacherCode(String code) {	
		return voteDao.insertTeacherCode(code);
	}
	@Override
	public int deleteTeacherCode() {
		return voteDao.deleteTeacherCode();
	}
	@Override
	public int updateTeacherCode(String code) {
		return voteDao.updateTeacherCode(code);
	}
	@Override
	public Integer checkTeacherCode(String code) {
		
		return voteDao.checkTeacherCode(code);
	}
	@Override
	public Integer checkTeacherCodeIsNull(String code) {

		return voteDao.checkTeacherCodeIsNull(code);
	}
	@Override
	public int createVote(List<Long> ids) {
		try {
			ids.forEach(o->{
				integerOperations.increment(VoteConstant.VOTE_TICKET+o);
			});
		} catch (Exception e) {
			e.printStackTrace();
			return 0;
		}
		if (saveCount.getAndAdd(1) >= VoteConstant.UPDATE_NUM){
			synchronized (saveCount){
				System.out.println("greater than 9");
				if (saveCount.get() >= VoteConstant.UPDATE_NUM ){
					saveCount.set(0);
					List<String> collect = StartupListenerConfig.ids.stream().map(o -> {
						return VoteConstant.VOTE_TICKET + o;
					}).collect(Collectors.toList());
					List<Integer> tickets = integerOperations.multiGet(collect);
					List<TicketSaveDO> list =new ArrayList<>(collect.size());
					for (int i = 0 ;i <StartupListenerConfig.ids.size();i++){
						if (tickets.get(i) != null){
							list.add(new TicketSaveDO(StartupListenerConfig.ids.get(i),tickets.get(i)));
						}
					}
					System.out.println("保存到数据库");
					return voteDao.saveVote(list);
				}
			}
		}
		return ids.size();
	}
	@Override
	public List<VoteListOffLineDO> getSum() {
		// TODO Auto-generated method stub
		try {
			List<String> collect = StartupListenerConfig.ids.stream()
					.map(o -> {
						return VoteConstant.VOTE_TICKET + o;
					}).collect(Collectors.toList());
			List<Integer> integers = integerOperations.multiGet(collect);
			List<VoteListOffLineDO> results = new ArrayList<>();
			for (int i=0;i<integers.size();i++){
				results.add(new VoteListOffLineDO(StartupListenerConfig.ids.get(i),integers.get(i)));
			}
//			throw new AppException("test for error");
			return results;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return voteDao.getSum();
	}
}
